<template>
  <div class="page-container-padding">
    <div class="module-auth">
      <div class="part-title">功能权限设置</div>
      <div class="actions">
        <el-select
          v-model="selectUserId"
          filterable
          remote
          size="mini"
          style="width: 300px"
          placeholder="输入用户号/手机号查询用户"
          :remote-method="queryUserList"
        >
          <el-option
            v-for="u in userList"
            :key="u.id"
            :value="u.id"
            :label="`${u.username}(${u.nickname})`"
          />
        </el-select>
        <el-button
          type="primary"
          size="mini"
          style="margin-left: 10px"
          :disabled="!selectUserId"
          :laoding="queryUserAuthLoading"
          @click="queryUserSectionAccess"
        >
          权限查询
        </el-button>
      </div>
      <div style="margin-top: 10px">
        <el-table :key="authSectionKey" border stripe :data="sectionList">
          <el-table-column prop="id" label="ID" width="100" />
          <el-table-column prop="sec_key" label="代码" width="120" />
          <el-table-column prop="sec_name" label="名称" />
          <el-table-column label="权限" width="100" />
          <el-table-column prop="expire_date" label="到期日" width="110" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-button
                v-if="scope.row.hasAccess"
                type="text"
                style="color: green"
                @click="toCloseAuth(scope.row)"
              >
                已开通
              </el-button>
              <el-button
                v-else
                type="text"
                style="color: red"
                @click="toOpenAuth(scope.row)"
              >
                开启
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="variety-auth">
      <div class="part-title">板块品种权限设置</div>
      <div class="actions">
        <el-select
          v-model="selectUserId"
          filterable
          remote
          size="mini"
          style="width: 300px"
          placeholder="输入用户号/手机号查询用户"
          :remote-method="queryUserList"
        >
          <el-option
            v-for="u in userList"
            :key="u.id"
            :value="u.id"
            :label="`${u.username}(${u.nickname})`"
          />
        </el-select>
        <el-select
          v-model="selectSecKey"
          size="mini"
          style="width: 300px; margin-left: 10px"
        >
          <el-option
            v-for="sec in sectionList"
            :key="sec.sec_key"
            :value="sec.sec_key"
            :label="sec.sec_name"
          />
        </el-select>
        <el-button
          type="primary"
          size="mini"
          style="margin-left: 10px"
          :disabled="!selectUserId || !selectSecKey"
          :laoding="queryUserSecVarietyAuthLoading"
          @click="queryUserSecVarietyAccess"
        >
          权限查询
        </el-button>
        <div style="margin-left: auto">
          <el-date-picker
            v-model="userSecVarietyAuth.expire_date"
            size="mini"
          />
          <el-button
            type="success"
            size="mini"
            style="margin-left: 6px"
            :loading="userSecVarietyAuth.saveLoading"
            @click="toOpenAllVarietyAuth"
          >
            开通全品种
          </el-button>
        </div>
      </div>
      <div v-loading="queryUserSecVarietyAuthLoading" style="margin-top: 10px">
        <el-table
          :key="authVarietyKey"
          border
          stripe
          :data="sectionVarietyList"
        >
          <el-table-column prop="id" label="ID" width="100" />
          <el-table-column prop="code" label="代码" width="100" />
          <el-table-column prop="group_name" label="组别" width="120" />
          <el-table-column prop="name" label="名称" />
          <el-table-column label="权限" width="100" />
          <el-table-column prop="expire_date" label="到期日" width="110" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-button
                v-if="scope.row.hasAccess"
                type="text"
                style="color: green"
                @click="toCloseVarietyAuth(scope.row)"
              >
                已开通
              </el-button>
              <el-button
                v-else
                type="text"
                style="color: red"
                @click="toOpenVarietyAuth(scope.row)"
              >
                开启
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 添加权限的弹窗 -->
    <el-dialog :visible.sync="userNewModulAuth.isShow" title="管理功能权限">
      <div style="padding: 15px 20px">
        <div>
          您正在给用户【
          <span style="color: red">{{ userNewModulAuth.userName }}</span>
          】新增权限【
          <span style="color: green">{{ userNewModulAuth.sec_name }}</span>
          】，请设定一个权限到期日。
        </div>
        <div style="margin-top: 10px">
          <span>权限到期日：</span>
          <el-date-picker
            v-model="userNewModulAuth.expire_date"
            size="mini"
            :clearable="false"
          />
        </div>
      </div>
      <div slot="footer">
        <el-button
          type="default"
          size="mini"
          @click="userNewModulAuth.isShow = false"
        >
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="saveOpenAuth">
          确定开通
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加板块品种权限的弹窗 -->
    <el-dialog
      :visible.sync="userSecVarietyAuth.isShow"
      title="管理板块内品种权限"
    >
      <div style="padding: 15px 20px">
        <div>
          您正在给用户【
          <span style="color: red">{{ userNewModulAuth.userName }}</span>
          】的【
          <span style="color: green">{{ userSecVarietyAuth.sec_name }}</span>
          】，新增【
          <span style="color: blue">{{ userSecVarietyAuth.variety_name }}</span>
          】的权限，请设定一个权限到期日。
        </div>
        <div style="margin-top: 10px">
          <span>权限到期日：</span>
          <el-date-picker
            v-model="userSecVarietyAuth.expire_date"
            size="mini"
            :clearable="false"
          />
        </div>
      </div>
      <div slot="footer">
        <el-button
          type="default"
          size="mini"
          @click="userSecVarietyAuth.isShow = false"
        >
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="saveSectionVarietyAuth">
          确定开通
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    RetrieveAuthSection,
    CreateUserSectionAuth,
    RetrieveUserSectionAuth,
    CreateUserSectionVarietyAuth,
    RetrieveUserSectionVarietyAuth,
  } from '@/api/adminRuizhi/auth'
  import {
    RetrieveUser,
    RetrieveVariety,
    RetrieveVarietyScopes,
  } from '@/api/adminRuizhi/common'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  export default {
    data() {
      return {
        authSectionKey: 0,
        authVarietyKey: 0,
        newSectionName: '',
        newSectionVarietyScope: '',
        saveLoading: false,
        varietyScopeList: [],
        userList: [],
        selectUserId: null,
        sectionList: [],
        hasAccesskeyList: [],
        userNewModulAuth: {
          userName: '',
          sec_key: '',
          sec_name: '',
          expire_date: new Date(),
          isShow: false,
        },
        queryUserAuthLoading: false,
        selectSecKey: '',
        selectSecVarietyScope: '',
        queryUserSecVarietyAuthLoading: false,
        sectionVarietyList: [],
        userSecVarietyAuth: {
          saveLoading: false,
          variety_en: '',
          sec_name: '',
          variety_name: '',
          expire_date: new Date(),
          isShow: false,
        },
      }
    },
    watch: {
      selectUserId(n) {
        for (let i = 0; i < this.userList.length; i++) {
          if (this.userList[i].id === n) {
            const u = this.userList[i]
            this.userNewModulAuth.userName = `${u.username}(${u.nickname})`
            break
          }
        }
        this.queryUserSectionAccess()
        if (this.selectUserId && this.selectSecKey) {
          this.queryUserSecVarietyAccess()
        }
      },
      selectSecKey(n) {
        for (let i = 0; i < this.sectionList.length; i++) {
          if (this.sectionList[i].sec_key === n) {
            this.userSecVarietyAuth.sec_name = this.sectionList[i].sec_name
            this.selectSecVarietyScope = this.sectionList[i].variety_scope
            break
          }
        }
        this.sectionVarietyList = []
        if (this.selectSecVarietyScope) {
          // 查询品种
          this.queryUserSecVarietyAuthLoading = true
          RetrieveVariety(null, this.selectSecVarietyScope).then((res) => {
            this.sectionVarietyList = res.data.data
            this.queryUserSecVarietyAuthLoading = false
            if (this.selectUserId && this.selectSecKey) {
              this.queryUserSecVarietyAccess()
            }
          })
        }
      },
    },
    mounted() {
      this.queryAuthSection()
      RetrieveVarietyScopes().then((res) => {
        this.varietyScopeList = res.data
      })
    },
    methods: {
      queryAuthSection() {
        RetrieveAuthSection().then((res) => {
          this.sectionList = res.data.data.map((item) => {
            item.hasAccess = false
            item.expire_date = ''
            return item
          })
        })
      },
      queryUserList(kw) {
        RetrieveUser(kw).then((res) => {
          this.userList = res.data.rows
        })
      },
      toOpenAuth(row) {
        if (!this.selectUserId) {
          this.$baseMessage('请选择用户后再设置!', 'error')
          return
        }
        this.userNewModulAuth.sec_name = row.sec_name
        this.userNewModulAuth.sec_key = row.sec_key
        this.userNewModulAuth.isShow = true
      },
      toCloseAuth(row) {
        this.$baseConfirm('确定关闭该权限吗?', '警告', () => {
          const yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
          const bData = {
            user_id: this.selectUserId,
            sec_key: row.sec_key,
            r_access: 0,
            expire_date: datetimeToStr(yesterday, true, '-'),
          }
          CreateUserSectionAuth(bData).then((res) => {
            this.$baseMessage(res.message, 'success')
            this.queryUserSectionAccess()
          })
        })
      },
      saveOpenAuth() {
        const bData = {
          user_id: this.selectUserId,
          sec_key: this.userNewModulAuth.sec_key,
          r_access: 1,
          expire_date: datetimeToStr(
            this.userNewModulAuth.expire_date,
            true,
            '-'
          ),
        }
        CreateUserSectionAuth(bData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.userNewModulAuth.isShow = false
          this.queryUserSectionAccess()
        })
      },
      // 查询用户模块权限
      queryUserSectionAccess() {
        this.queryUserAuthLoading = true
        RetrieveUserSectionAuth(this.selectUserId).then((res) => {
          const authList = res.data.data
          for (let i = 0; i < this.sectionList.length; i++) {
            const sobj = this.sectionList[i]
            sobj.expire_date = ''
            sobj.hasAccess = false
            for (let j = 0; j < authList.length; j++) {
              const oj = authList[j]
              if (sobj.sec_key === oj.sec_key) {
                sobj.hasAccess = true
                sobj.expire_date = oj.expire_date
                break
              }
            }
          }
          this.authSectionKey = new Date().getTime()
          this.queryUserAuthLoading = false
        })
      },
      toOpenAllVarietyAuth() {
        this.userSecVarietyAuth.saveLoading = true
        CreateUserSectionVarietyAuth({
          user_id: this.selectUserId,
          sec_key: this.selectSecKey,
          variety_en: 'VAR_ALL',
          r_access: 1,
          expire_date: datetimeToStr(
            this.userSecVarietyAuth.expire_date,
            true,
            '-'
          ),
        })
          .then((res) => {
            this.$baseMessage(res.message, 'success')
            this.queryUserSecVarietyAccess()
            this.userSecVarietyAuth.saveLoading = false
          })
          .catch(() => {
            this.userSecVarietyAuth.saveLoading = false
          })
      },

      toOpenVarietyAuth(row) {
        if (!this.selectUserId || !this.selectSecKey) {
          this.$baseMessage('请选择用户和板块后再设置!', 'error')
          return
        }
        this.userSecVarietyAuth.variety_en = row.code
        this.userSecVarietyAuth.variety_name = row.name
        this.userSecVarietyAuth.isShow = true
      },
      toCloseVarietyAuth(row) {
        this.$baseConfirm('确定关闭该品种权限吗?', '警告', () => {
          const yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
          const bData = {
            user_id: this.selectUserId,
            sec_key: this.selectSecKey,
            variety_en: row.code,
            r_access: 0,
            expire_date: datetimeToStr(yesterday, true, '-'),
          }
          CreateUserSectionVarietyAuth(bData).then((res) => {
            this.$baseMessage(res.message, 'success')
            this.queryUserSecVarietyAccess()
          })
        })
      },
      saveSectionVarietyAuth() {
        const bData = {
          user_id: this.selectUserId,
          sec_key: this.selectSecKey,
          variety_en: this.userSecVarietyAuth.variety_en,
          r_access: 1,
          expire_date: datetimeToStr(
            this.userSecVarietyAuth.expire_date,
            true,
            '-'
          ),
        }
        CreateUserSectionVarietyAuth(bData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.userSecVarietyAuth.isShow = false
          this.queryUserSecVarietyAccess()
        })
      },
      // 用户模块品种权限
      queryUserSecVarietyAccess() {
        this.queryUserSecVarietyAuthLoading = true
        RetrieveUserSectionVarietyAuth(
          this.selectUserId,
          this.selectSecKey
        ).then((res) => {
          // console.log(res)
          let allVarietyExpire = new Date()
          const authList = res.data.data
          for (let i = 0; i < this.sectionVarietyList.length; i++) {
            const vobj = this.sectionVarietyList[i]
            vobj.expire_date = ''
            vobj.hasAccess = false
            for (let j = 0; j < authList.length; j++) {
              const oj = authList[j]
              if (oj.variety_en === 'VAR_ALL') {
                allVarietyExpire = new Date(oj.expire_date)
              }
              if (vobj.code === oj.variety_en) {
                vobj.hasAccess = true
                vobj.expire_date = oj.expire_date
                break
              }
            }
          }
          this.authVarietyKey = new Date().getTime()
          this.queryUserSecVarietyAuthLoading = false
          this.userSecVarietyAuth.expire_date = allVarietyExpire
        })
      },
    },
  }
</script>
<style scoped lang="scss">
  .page-container-padding {
    .part-title {
      padding-left: 10px;
      background-color: #eee;
      line-height: 22px;
      color: #ff9800;
    }
    .new-module {
      display: flex;
      align-items: center;
      margin-top: 10px;
    }
    .module-auth {
      margin-top: 10px;
      .actions {
        display: flex;
        align-items: center;
        margin-top: 10px;
      }
    }
    .variety-auth {
      margin-top: 10px;
      .actions {
        display: flex;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
</style>
